<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>简易星空图</title>
</head>
<body>
<canvas id="c" style="background:#000"></canvas>
</body>
</html>
<script>
    var Num = 100;
var points = [];
// 查找元素
var c = document.querySelector('#c');
// 创建context 对象 拥有多种绘制路径 矩形 字符以及添加图像的方法
var ctx = c.getContext('2d');
// 宽度
var w = c.width = window.innerWidth;
// 高度
var h = c.height = window.innerHeight;
var point = function() {
    this.x = Math.random() * w;
    this.y = Math.random() * h;
    this.color = Math.random() * 360;
    this.count = 5;
    this.mindis = 100;
    this.speedx = Math.random() * 2 - 1;
    this.speedy = Math.random() * 2 - 1;
    //this.bound=false;
}
point.prototype.constructor = point;
point.prototype.lineTo = function(points) {
    // console.log('lineTo')
    // 绘制路径
    ctx.beginPath();
    for (var i in points) {
        // 斜边长度
        var dis = Math.sqrt(Math.pow((this.x - points[i].x), 2) + Math.pow((this.y - points[i].y), 2));
        if (this.count > 0 && points[i].count > 0 && dis < this.mindis) {
            // 线条渐变
            var grd = ctx.createLinearGradient(this.x, this.y, points[i].x, points[i].y);
            var o = dis * 0.8 / this.mindis + 0.2;
            // 颜色停止
            grd.addColorStop(0, "hsla(" + this.color + ",100%,50%," + o + ")");
            grd.addColorStop(1, "hsla(" + points[i].color + ",100%,50%," + o + ")");
            // 笔触颜色
            ctx.strokeStyle = grd;
            // 线条开始坐标
            ctx.moveTo(this.x, this.y);
            // 线条结束坐标
            ctx.lineTo(points[i].x, points[i].y);
            // 绘制路径
            ctx.stroke();
            this.count--;
            points[i].count--;
        }
    }
    // 当前点回到起始点的路径
    ctx.closePath();
};
point.prototype.init = function() {
    // console.log(init)
    this.x += this.speedx;
    this.y += this.speedy;
    this.count = 6;
};
point.prototype.isBound = function() {
    // console.log('isBound')
    if (this.x < 0 || this.x > w) {
        //this.bound=true;
        this.speedx = -this.speedx;

    } else if (this.y < 0 || this.y > h) {
        this.speedy = -this.speedy;
    }
};
(function createPoints() {
    // console.log('reatePoints')
    for (var i = 0; i < Num; i++) {
        points.push(new point());
    }
})();

function drawPoints() {
    // console.log('drawPoints')
    ctx.clearRect(0, 0, w, h);
    for (var i in points) {
        var p = points[i];
        //if(!parseInt(Math.random()*4,10)){
        //	p.init();
        //}	
        p.isBound();
        p.init();
        //p.count=5;
        ctx.fillStyle = "hsla(" + p.color + ",100%,50%,1)";
        ctx.fillRect(p.x - 1, p.y - 1, 2, 2);
        p.lineTo(points);
    }
}

setInterval(drawPoints, 100)
</script>
<!--
   createPoints drawPoints  isBound   init lineTo
-->